/**
 * 钓鱼天堂 - 论坛功能脚本
 * 处理论坛相关的数据操作和UI交互
 */

// 页面加载完成后初始化论坛功能
document.addEventListener('DOMContentLoaded', function() {
    // 根据当前页面类型初始化不同的功能
    if (window.location.pathname.includes('forum.html')) {
        initializeForumPage();
    } else if (window.location.pathname.includes('post.html')) {
        initializePostPage();
    } else if (window.location.pathname.includes('index.html') || window.location.pathname === '/' || window.location.pathname.endsWith('/')) {
        // 首页上可能也有论坛部分，初始化首页论坛模块
        initializeHomeForumSection();
    }
});

/**
 * 初始化论坛首页功能
 */
function initializeForumPage() {
    console.log('初始化论坛页面');
    
    // 加载论坛板块
    loadForumSections();
    
    // 加载热门帖子
    loadHotPosts();
    
    // 加载最新帖子
    loadLatestPosts();
    
    // 设置发布新帖功能
    setupNewPostForm();
    
    // 设置帖子搜索功能
    setupPostSearch();
}

/**
 * 初始化帖子详情页面
 */
function initializePostPage() {
    console.log('初始化帖子详情页面');
    
    // 获取帖子ID
    const urlParams = new URLSearchParams(window.location.search);
    const postId = urlParams.get('id');
    
    if (postId) {
        // 加载帖子详情
        loadPostDetails(postId);
        
        // 设置评论功能
        setupCommentForm(postId);
        
        // 加载相关推荐帖子
        loadRelatedPosts(postId);
    } else {
        // 如果没有帖子ID，重定向到论坛首页
        window.location.href = 'forum.html';
    }
}

/**
 * 初始化首页论坛部分
 */
function initializeHomeForumSection() {
    console.log('初始化首页论坛模块');
    
    // 在首页加载最新帖子预览
    loadLatestPostsPreview();
}

/**
 * 加载论坛板块数据
 */
function loadForumSections() {
    // 从localStorage获取板块数据，如果没有则使用默认数据
    let sections = JSON.parse(localStorage.getItem('forumSections'));
    
    // 如果没有数据，创建默认板块
    if (!sections) {
        sections = [
            {
                id: 'freshwater',
                name: '淡水钓鱼',
                description: '关于河流、湖泊等淡水区域的钓鱼讨论',
                icon: 'fas fa-water',
                color: 'bg-blue-100 text-blue-600',
                members: 2400,
                posts: 5600
            },
            {
                id: 'sea',
                name: '海钓',
                description: '海域钓鱼、船钓和岸钓的经验分享',
                icon: 'fas fa-ship',
                color: 'bg-indigo-100 text-indigo-600',
                members: 1800,
                posts: 3200
            },
            {
                id: 'equipment',
                name: '装备讨论',
                description: '钓鱼装备的选购建议和使用心得',
                icon: 'fas fa-toolbox',
                color: 'bg-green-100 text-green-600',
                members: 3100,
                posts: 7800
            },
            {
                id: 'technique',
                name: '钓技研究',
                description: '钓鱼技巧和方法的研究与分享',
                icon: 'fas fa-graduation-cap',
                color: 'bg-purple-100 text-purple-600',
                members: 2900,
                posts: 4500
            }
        ];
        
        // 保存到localStorage
        localStorage.setItem('forumSections', JSON.stringify(sections));
    }
    
    // 获取板块容器元素
    const sectionsContainer = document.getElementById('forum-sections');
    if (!sectionsContainer) return;
    
    // 清空容器
    sectionsContainer.innerHTML = '';
    
    // 渲染板块
    sections.forEach(section => {
        const sectionElement = document.createElement('div');
        sectionElement.className = 'bg-white rounded-lg shadow-md overflow-hidden hover:shadow-xl transition duration-300 transform hover:-translate-y-1';
        sectionElement.innerHTML = `
            <a href="forum.html?section=${section.id}">
                <img src="https://picsum.photos/400/200?${section.id}" alt="${section.name}" class="w-full h-40 object-cover">
                <div class="p-5">
                    <div class="flex items-center mb-3">
                        <div class="${section.color} w-10 h-10 rounded-full flex items-center justify-center mr-3">
                            <i class="${section.icon}"></i>
                        </div>
                        <h3 class="text-xl font-bold">${section.name}</h3>
                    </div>
                    <p class="text-gray-600 mb-4">${section.description}</p>
                    <div class="flex justify-between text-sm text-gray-500">
                        <span><i class="fas fa-users mr-1"></i> ${section.members.toLocaleString()} 成员</span>
                        <span><i class="fas fa-comments mr-1"></i> ${section.posts.toLocaleString()} 帖子</span>
                    </div>
                </div>
            </a>
        `;
        sectionsContainer.appendChild(sectionElement);
    });
}

/**
 * 加载热门帖子
 */
function loadHotPosts() {
    // 从localStorage获取帖子数据
    let posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    
    // 如果没有帖子数据，创建默认数据
    if (posts.length === 0) {
        createDefaultPosts();
        posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    }
    
    // 筛选出热门帖子（根据浏览量和点赞数）
    const hotPosts = posts
        .sort((a, b) => {
            const scoreA = (a.views || 0) + (a.likes || 0) * 2;
            const scoreB = (b.views || 0) + (b.likes || 0) * 2;
            return scoreB - scoreA;
        })
        .slice(0, 3);
    
    // 获取热门帖子容器
    const hotPostsContainer = document.getElementById('hot-posts');
    if (!hotPostsContainer) return;
    
    // 清空容器
    hotPostsContainer.innerHTML = '';
    
    // 渲染热门帖子
    hotPosts.forEach(post => {
        const postElement = document.createElement('div');
        postElement.className = 'p-4 hover:bg-gray-50 transition';
        postElement.innerHTML = `
            <div class="flex items-start">
                <div class="flex-shrink-0 mr-4">
                    <div class="bg-blue-100 text-blue-600 w-10 h-10 rounded-full flex items-center justify-center">
                        <i class="fas fa-fire"></i>
                    </div>
                </div>
                <div class="flex-1 min-w-0">
                    <h3 class="text-lg font-medium text-gray-900 mb-1">
                        <a href="post.html?id=${post.id}" class="hover:text-blue-600">${post.title}</a>
                    </h3>
                    <div class="flex flex-wrap items-center text-sm text-gray-500">
                        <span class="mr-3"><i class="fas fa-user mr-1"></i>${post.author}</span>
                        <span class="mr-3"><i class="far fa-clock mr-1"></i>${formatDate(post.date)}</span>
                        <span class="mr-3"><i class="fas fa-tag mr-1"></i>${post.section}</span>
                    </div>
                </div>
                <div class="ml-4 flex flex-col items-end">
                    <div class="flex space-x-4 text-sm text-gray-500">
                        <span><i class="far fa-thumbs-up mr-1"></i>${post.likes || 0}</span>
                        <span><i class="far fa-comment mr-1"></i>${post.comments ? post.comments.length : 0}</span>
                        <span><i class="far fa-eye mr-1"></i>${post.views || 0}</span>
                    </div>
                </div>
            </div>
        `;
        hotPostsContainer.appendChild(postElement);
    });
}

/**
 * 加载最新帖子
 */
function loadLatestPosts() {
    // 从localStorage获取帖子数据
    let posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    
    // 如果没有帖子数据，创建默认数据
    if (posts.length === 0) {
        createDefaultPosts();
        posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    }
    
    // 按日期排序，获取最新帖子
    const latestPosts = posts
        .sort((a, b) => new Date(b.date) - new Date(a.date))
        .slice(0, 4);
    
    // 获取最新帖子容器
    const latestPostsContainer = document.getElementById('latest-posts');
    if (!latestPostsContainer) return;
    
    // 清空容器
    latestPostsContainer.innerHTML = '';
    
    // 渲染最新帖子
    latestPosts.forEach(post => {
        const postElement = document.createElement('div');
        postElement.className = 'p-4 hover:bg-gray-50 transition';
        postElement.innerHTML = `
            <div class="flex items-start">
                <div class="flex-shrink-0 mr-4">
                    <img src="${post.authorAvatar || `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/200/200`}" alt="${post.author}" class="w-10 h-10 rounded-full">
                </div>
                <div class="flex-1 min-w-0">
                    <h3 class="text-lg font-medium text-gray-900 mb-1">
                        <a href="post.html?id=${post.id}" class="hover:text-blue-600">${post.title}</a>
                    </h3>
                    <div class="flex flex-wrap items-center text-sm text-gray-500">
                        <span class="mr-3"><i class="fas fa-user mr-1"></i>${post.author}</span>
                        <span class="mr-3"><i class="far fa-clock mr-1"></i>${formatDate(post.date)}</span>
                        <span class="mr-3"><i class="fas fa-tag mr-1"></i>${post.section}</span>
                    </div>
                </div>
                <div class="ml-4 flex flex-col items-end">
                    <div class="flex space-x-4 text-sm text-gray-500">
                        <span><i class="far fa-thumbs-up mr-1"></i>${post.likes || 0}</span>
                        <span><i class="far fa-comment mr-1"></i>${post.comments ? post.comments.length : 0}</span>
                        <span><i class="far fa-eye mr-1"></i>${post.views || 0}</span>
                    </div>
                </div>
            </div>
        `;
        latestPostsContainer.appendChild(postElement);
    });
}

/**
 * 加载首页上的最新帖子预览
 */
function loadLatestPostsPreview() {
    // 从localStorage获取帖子数据
    let posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    
    // 如果没有帖子数据，创建默认数据
    if (posts.length === 0) {
        createDefaultPosts();
        posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    }
    
    // 按日期排序，获取最新帖子
    const latestPosts = posts
        .sort((a, b) => new Date(b.date) - new Date(a.date))
        .slice(0, 4);
    
    // 获取首页最新帖子容器
    const latestPostsContainer = document.getElementById('latest-posts');
    if (!latestPostsContainer) return;
    
    // 清空容器
    latestPostsContainer.innerHTML = '';
    
    // 渲染最新帖子预览
    latestPosts.forEach(post => {
        const postElement = document.createElement('div');
        postElement.className = 'border-b border-gray-200 pb-4';
        postElement.innerHTML = `
            <div class="flex justify-between items-start">
                <div>
                    <h3 class="font-bold text-lg mb-1">
                        <a href="post.html?id=${post.id}" class="hover:text-blue-600 transition">${post.title}</a>
                    </h3>
                    <p class="text-sm text-gray-500">
                        <span class="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded mr-2">${post.section}</span>
                        <span class="mr-2"><i class="fas fa-user mr-1"></i>${post.author}</span>
                        <span><i class="far fa-calendar mr-1"></i>${formatDate(post.date)}</span>
                    </p>
                </div>
                <div class="text-sm text-gray-500">
                    <span class="mr-3"><i class="far fa-thumbs-up mr-1"></i>${post.likes || 0}</span>
                    <span><i class="far fa-comment mr-1"></i>${post.comments ? post.comments.length : 0}</span>
                </div>
            </div>
        `;
        latestPostsContainer.appendChild(postElement);
    });
}

/**
 * 加载帖子详情
 * @param {string} postId 帖子ID
 */
function loadPostDetails(postId) {
    // 从localStorage获取帖子数据
    const posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    const post = posts.find(p => p.id === postId);
    
    if (!post) {
        // 如果找不到帖子，跳转到论坛首页
        window.location.href = 'forum.html';
        return;
    }
    
    // 更新页面标题
    document.title = `${post.title} - 钓鱼论坛`;
    
    // 更新帖子内容
    const elements = {
        title: document.getElementById('post-title'),
        titleBreadcrumb: document.getElementById('post-title-breadcrumb'),
        section: document.getElementById('post-section'),
        sectionBreadcrumb: document.getElementById('post-section-breadcrumb'),
        date: document.getElementById('post-date'),
        views: document.getElementById('post-views'),
        commentsCount: document.getElementById('post-comments-count'),
        commentCount: document.getElementById('comment-count'),
        author: document.getElementById('post-author'),
        authorAvatar: document.getElementById('post-author-avatar'),
        content: document.getElementById('post-content'),
        likesCount: document.getElementById('post-likes-count')
    };
    
    // 更新元素内容
    if (elements.title) elements.title.textContent = post.title;
    if (elements.titleBreadcrumb) elements.titleBreadcrumb.textContent = post.title;
    if (elements.section) elements.section.textContent = post.section;
    if (elements.sectionBreadcrumb) elements.sectionBreadcrumb.textContent = post.section;
    if (elements.date) elements.date.innerHTML = `<i class="far fa-calendar mr-1"></i>${formatDate(post.date)}`;
    if (elements.views) elements.views.innerHTML = `<i class="far fa-eye mr-1"></i>${post.views || 0} 浏览`;
    if (elements.commentsCount) elements.commentsCount.innerHTML = `<i class="far fa-comment mr-1"></i>${post.comments ? post.comments.length : 0} 评论`;
    if (elements.commentCount) elements.commentCount.textContent = `(${post.comments ? post.comments.length : 0})`;
    if (elements.author) elements.author.textContent = post.author;
    if (elements.authorAvatar) elements.authorAvatar.src = post.authorAvatar || `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/200/200`;
    if (elements.content) elements.content.innerHTML = post.content;
    if (elements.likesCount) elements.likesCount.textContent = post.likes || 0;
    
    // 设置分享链接
    const shareLink = document.getElementById('share-link');
    if (shareLink) shareLink.value = window.location.href;
    
    // 增加浏览量
    incrementViewCount(postId);
    
    // 显示评论
    loadComments(post);
}

/**
 * 加载帖子的评论
 * @param {Object} post 帖子对象
 */
function loadComments(post) {
    const commentsContainer = document.getElementById('comments-list');
    if (!commentsContainer) return;
    
    // 清空容器
    commentsContainer.innerHTML = '';
    
    // 如果没有评论，显示提示
    if (!post.comments || post.comments.length === 0) {
        commentsContainer.innerHTML = `
            <div class="p-6 text-center text-gray-500">
                <i class="far fa-comment-dots text-4xl mb-2"></i>
                <p>暂无评论，来发表第一条评论吧！</p>
            </div>
        `;
        return;
    }
    
    // 渲染评论
    post.comments.forEach((comment, index) => {
        const commentElement = document.createElement('div');
        commentElement.className = 'p-6';
        commentElement.innerHTML = `
            <div class="flex">
                <div class="flex-shrink-0 mr-4">
                    <img src="${comment.authorAvatar || `https://picsum.photos/id/${50 + index}/200/200`}" alt="${comment.author}" class="w-10 h-10 rounded-full">
                </div>
                <div class="flex-1">
                    <div class="flex items-center mb-1">
                        <h4 class="font-medium mr-2">${comment.author}</h4>
                        <span class="text-xs text-gray-500">${formatDate(comment.date)}</span>
                        <span class="text-xs text-gray-500 ml-auto">#${index + 1}</span>
                    </div>
                    <div class="text-gray-800 mb-3">${comment.content}</div>
                    <div class="flex items-center text-sm text-gray-500">
                        <button class="comment-like-btn mr-4 hover:text-blue-600 transition" data-comment-id="${comment.id}">
                            <i class="far fa-thumbs-up mr-1"></i>
                            <span>${comment.likes || 0}</span>
                        </button>
                        <button class="comment-reply-btn hover:text-blue-600 transition" data-comment-id="${comment.id}">
                            <i class="far fa-comment mr-1"></i>回复
                        </button>
                    </div>
                </div>
            </div>
        `;
        commentsContainer.appendChild(commentElement);
    });
    
    // 添加评论点赞功能
    setupCommentLikes(post.id);
    
    // 添加评论回复功能
    setupCommentReplies(post);
}

/**
 * 设置评论点赞功能
 * @param {string} postId 帖子ID
 */
function setupCommentLikes(postId) {
    const likeButtons = document.querySelectorAll('.comment-like-btn');
    
    likeButtons.forEach(button => {
        button.addEventListener('click', function() {
            const commentId = this.getAttribute('data-comment-id');
            const likeCountElement = this.querySelector('span');
            let likeCount = parseInt(likeCountElement.textContent);
            likeCount += 1;
            likeCountElement.textContent = likeCount;
            
            // 更新评论点赞数
            updateCommentLikes(postId, commentId, likeCount);
            
            // 显示点赞动画
            const icon = this.querySelector('i');
            icon.classList.remove('far');
            icon.classList.add('fas', 'text-blue-600');
        });
    });
}

/**
 * 设置评论回复功能
 * @param {Object} post 帖子对象
 */
function setupCommentReplies(post) {
    const replyButtons = document.querySelectorAll('.comment-reply-btn');
    
    replyButtons.forEach(button => {
        button.addEventListener('click', function() {
            const commentId = this.getAttribute('data-comment-id');
            const comment = post.comments.find(c => c.id === commentId);
            
            if (comment) {
                const textarea = document.getElementById('comment-content');
                if (textarea) {
                    textarea.value = `@${comment.author} `;
                    textarea.focus();
                    
                    // 滚动到评论表单
                    const commentForm = document.getElementById('comment-form');
                    if (commentForm) {
                        commentForm.scrollIntoView({behavior: 'smooth'});
                    }
                }
            }
        });
    });
}

/**
 * 更新评论点赞数
 * @param {string} postId 帖子ID
 * @param {string} commentId 评论ID
 * @param {number} newLikeCount 新的点赞数
 */
function updateCommentLikes(postId, commentId, newLikeCount) {
    // 从localStorage获取帖子
    const posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    const postIndex = posts.findIndex(p => p.id === postId);
    
    if (postIndex !== -1) {
        const post = posts[postIndex];
        if (post.comments) {
            const commentIndex = post.comments.findIndex(c => c.id === commentId);
            
            if (commentIndex !== -1) {
                post.comments[commentIndex].likes = newLikeCount;
                localStorage.setItem('forumPosts', JSON.stringify(posts));
            }
        }
    }
}

/**
 * 增加帖子浏览量
 * @param {string} postId 帖子ID
 */
function incrementViewCount(postId) {
    // 从localStorage获取帖子
    const posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    const postIndex = posts.findIndex(p => p.id === postId);
    
    if (postIndex !== -1) {
        const post = posts[postIndex];
        post.views = (post.views || 0) + 1;
        localStorage.setItem('forumPosts', JSON.stringify(posts));
        
        // 更新显示
        const viewsElement = document.getElementById('post-views');
        if (viewsElement) {
            viewsElement.innerHTML = `<i class="far fa-eye mr-1"></i>${post.views} 浏览`;
        }
    }
}

/**
 * 设置评论表单功能
 * @param {string} postId 帖子ID
 */
function setupCommentForm(postId) {
    const submitCommentBtn = document.getElementById('submit-comment');
    if (!submitCommentBtn) return;
    
    submitCommentBtn.addEventListener('click', function() {
        const user = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null;
        
        if (!user) {
            showNotification('请先登录后再发表评论', 'error');
            return;
        }
        
        const commentContent = document.getElementById('comment-content').value.trim();
        const commentError = document.getElementById('comment-error');
        
        if (!commentContent) {
            if (commentError) commentError.classList.remove('hidden');
            return;
        } else {
            if (commentError) commentError.classList.add('hidden');
        }
        
        // 添加新评论
        addComment(postId, {
            id: 'c' + Date.now(),
            author: user.username,
            authorAvatar: user.avatar,
            content: commentContent,
            date: new Date().toISOString(),
            likes: 0
        });
        
        // 清空评论框
        document.getElementById('comment-content').value = '';
        
        // 显示通知
        showNotification('评论发布成功！');
    });
}

/**
 * 添加评论
 * @param {string} postId 帖子ID
 * @param {Object} comment 评论对象
 */
function addComment(postId, comment) {
    // 从localStorage获取帖子
    const posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    const postIndex = posts.findIndex(p => p.id === postId);
    
    if (postIndex !== -1) {
        const post = posts[postIndex];
        
        // 如果没有评论数组，创建一个
        if (!post.comments) {
            post.comments = [];
        }
        
        // 添加新评论
        post.comments.push(comment);
        
        // 保存到localStorage
        localStorage.setItem('forumPosts', JSON.stringify(posts));
        
        // 重新加载评论
        loadComments(post);
        
        // 更新评论数显示
        const commentsCountElement = document.getElementById('post-comments-count');
        if (commentsCountElement) {
            commentsCountElement.innerHTML = `<i class="far fa-comment mr-1"></i>${post.comments.length} 评论`;
        }
        
        const commentCountElement = document.getElementById('comment-count');
        if (commentCountElement) {
            commentCountElement.textContent = `(${post.comments.length})`;
        }
    }
}

/**
 * 加载相关推荐帖子
 * @param {string} currentPostId 当前帖子ID
 */
function loadRelatedPosts(currentPostId) {
    // 从localStorage获取所有帖子
    const posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    
    // 获取当前帖子，用于找到相关帖子
    const currentPost = posts.find(p => p.id === currentPostId);
    if (!currentPost) return;
    
    // 按相关性排序（同一板块、相似标题）并排除当前帖子
    const relatedPosts = posts
        .filter(post => post.id !== currentPostId)
        .sort((a, b) => {
            let scoreA = 0;
            let scoreB = 0;
            
            // 同一板块加分
            if (a.section === currentPost.section) scoreA += 10;
            if (b.section === currentPost.section) scoreB += 10;
            
            // 标题相似度加分
            const titleWordsA = a.title.toLowerCase().split(' ');
            const titleWordsB = b.title.toLowerCase().split(' ');
            const currentTitleWords = currentPost.title.toLowerCase().split(' ');
            
            currentTitleWords.forEach(word => {
                if (titleWordsA.includes(word)) scoreA += 5;
                if (titleWordsB.includes(word)) scoreB += 5;
            });
            
            return scoreB - scoreA;
        })
        .slice(0, 3);
    
    // 获取推荐帖子容器
    const recommendedContainer = document.getElementById('recommended-posts');
    if (!recommendedContainer) return;
    
    // 清空容器
    recommendedContainer.innerHTML = '';
    
    // 如果没有相关帖子，显示一些默认帖子
    if (relatedPosts.length === 0) {
        const defaultPosts = [
            {
                id: "101",
                title: "夏季钓鱼的最佳时间",
                author: "四季钓手",
                date: "2025-04-28",
                section: "钓技研究",
                views: 122
            },
            {
                id: "102",
                title: "自制鲫鱼饵料配方分享",
                author: "饵料专家",
                date: "2025-04-30",
                section: "淡水钓鱼",
                views: 145
            },
            {
                id: "103",
                title: "新手必读：钓具选购指南",
                author: "渔具店老板",
                date: "2025-05-02",
                section: "装备讨论",
                views: 198
            }
        ];
        
        defaultPosts.forEach(post => {
            createRecommendedPostCard(post, recommendedContainer);
        });
    } else {
        // 渲染相关帖子
        relatedPosts.forEach(post => {
            createRecommendedPostCard(post, recommendedContainer);
        });
    }
}

/**
 * 创建推荐帖子卡片
 * @param {Object} post 帖子对象
 * @param {HTMLElement} container 容器元素
 */
function createRecommendedPostCard(post, container) {
    const postCard = document.createElement('div');
    postCard.className = 'bg-white rounded-lg shadow-md overflow-hidden hover:shadow-lg transition duration-300';
    postCard.innerHTML = `
        <a href="post.html?id=${post.id}" class="block">
            <div class="p-5">
                <h3 class="font-bold text-lg mb-2 line-clamp-2 hover:text-blue-600 transition">${post.title}</h3>
                <div class="flex justify-between text-sm text-gray-500">
                    <span><i class="fas fa-user mr-1"></i>${post.author}</span>
                    <span><i class="fas fa-tag mr-1"></i>${post.section}</span>
                </div>
            </div>
        </a>
    `;
    container.appendChild(postCard);
}

/**
 * 设置新帖表单功能
 */
function setupNewPostForm() {
    const newPostBtn = document.getElementById('new-post-btn');
    if (!newPostBtn) return;
    
    const postModal = document.getElementById('post-modal');
    const closePostModal = document.getElementById('close-post-modal');
    const cancelPost = document.getElementById('cancel-post');
    const newPostForm = document.getElementById('new-post-form');
    
    // 打开发布帖子模态框
    newPostBtn.addEventListener('click', function() {
        const user = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null;
        
        if (!user) {
            window.location.href = 'auth.html';
            return;
        }
        
        if (postModal) postModal.classList.remove('hidden');
    });
    
    // 关闭模态框
    if (closePostModal) {
        closePostModal.addEventListener('click', function() {
            if (postModal) postModal.classList.add('hidden');
        });
    }
    
    // 取消发布
    if (cancelPost) {
        cancelPost.addEventListener('click', function() {
            if (postModal) postModal.classList.add('hidden');
        });
    }
    
    // 提交新帖表单
    if (newPostForm) {
        newPostForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const title = document.getElementById('post-title').value.trim();
            const section = document.getElementById('post-section').value;
            const content = document.getElementById('post-content').value.trim();
            const user = JSON.parse(localStorage.getItem('currentUser'));
            
            if (!title || !section || !content) {
                return;
            }
            
            // 创建新帖子
            const newPost = {
                id: Date.now().toString(),
                title: title,
                content: `<p>${content.replace(/\n/g, '</p><p>')}</p>`,
                author: user.username,
                authorAvatar: user.avatar,
                date: new Date().toISOString(),
                section: getSectionName(section),
                sectionId: section,
                likes: 0,
                comments: [],
                views: 0
            };
            
            // 获取现有帖子
            let posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
            
            // 添加到帖子列表
            posts.unshift(newPost);
            
            // 保存到localStorage
            localStorage.setItem('forumPosts', JSON.stringify(posts));
            
            // 关闭模态框
            if (postModal) postModal.classList.add('hidden');
            
            // 重置表单
            newPostForm.reset();
            
            // 重新加载最新帖子
            loadLatestPosts();
            
            // 显示成功通知
            showNotification('帖子发布成功！');
        });
    }
}

/**
 * 设置帖子搜索功能
 */
function setupPostSearch() {
    const searchInput = document.querySelector('input[placeholder="搜索帖子..."]');
    const searchBtn = searchInput ? searchInput.nextElementSibling : null;
    
    if (searchBtn) {
        searchBtn.addEventListener('click', function() {
            const searchTerm = searchInput.value.trim().toLowerCase();
            if (!searchTerm) return;
            
            // 搜索帖子
            searchPosts(searchTerm);
        });
    }
    
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                const searchTerm = searchInput.value.trim().toLowerCase();
                if (!searchTerm) return;
                
                // 搜索帖子
                searchPosts(searchTerm);
            }
        });
    }
}

/**
 * 搜索帖子
 * @param {string} searchTerm 搜索关键词
 */
function searchPosts(searchTerm) {
    // 从localStorage获取所有帖子
    const posts = JSON.parse(localStorage.getItem('forumPosts') || '[]');
    
    // 根据关键词筛选帖子
    const filteredPosts = posts.filter(post => {
        return post.title.toLowerCase().includes(searchTerm) || 
               post.content.toLowerCase().includes(searchTerm) ||
               post.author.toLowerCase().includes(searchTerm) ||
               post.section.toLowerCase().includes(searchTerm);
    });
    
    // 获取最新帖子容器
    const latestPostsContainer = document.getElementById('latest-posts');
    if (!latestPostsContainer) return;
    
    // 清空容器
    latestPostsContainer.innerHTML = '';
    
    // 如果没有搜索结果
    if (filteredPosts.length === 0) {
        latestPostsContainer.innerHTML = `
            <div class="p-10 text-center">
                <i class="fas fa-search text-gray-300 text-5xl mb-4"></i>
                <h3 class="text-xl font-bold text-gray-600 mb-2">没有找到相关帖子</h3>
                <p class="text-gray-500">尝试其他关键词或者浏览全部帖子</p>
            </div>
        `;
        return;
    }
    
    // 显示搜索结果
    filteredPosts.forEach(post => {
        const postElement = document.createElement('div');
        postElement.className = 'p-4 hover:bg-gray-50 transition';
        postElement.innerHTML = `
            <div class="flex items-start">
                <div class="flex-shrink-0 mr-4">
                    <img src="${post.authorAvatar || `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/200/200`}" alt="${post.author}" class="w-10 h-10 rounded-full">
                </div>
                <div class="flex-1 min-w-0">
                    <h3 class="text-lg font-medium text-gray-900 mb-1">
                        <a href="post.html?id=${post.id}" class="hover:text-blue-600">${post.title}</a>
                    </h3>
                    <div class="flex flex-wrap items-center text-sm text-gray-500">
                        <span class="mr-3"><i class="fas fa-user mr-1"></i>${post.author}</span>
                        <span class="mr-3"><i class="far fa-clock mr-1"></i>${formatDate(post.date)}</span>
                        <span class="mr-3"><i class="fas fa-tag mr-1"></i>${post.section}</span>
                    </div>
                </div>
                <div class="ml-4 flex flex-col items-end">
                    <div class="flex space-x-4 text-sm text-gray-500">
                        <span><i class="far fa-thumbs-up mr-1"></i>${post.likes || 0}</span>
                        <span><i class="far fa-comment mr-1"></i>${post.comments ? post.comments.length : 0}</span>
                        <span><i class="far fa-eye mr-1"></i>${post.views || 0}</span>
                    </div>
                </div>
            </div>
        `;
        latestPostsContainer.appendChild(postElement);
    });
    
    // 显示搜索结果提示
    const searchResultInfo = document.createElement('div');
    searchResultInfo.className = 'bg-blue-50 text-blue-600 p-2 rounded mb-4';
    searchResultInfo.innerHTML = `搜索结果：找到 ${filteredPosts.length} 个与"${searchTerm}"相关的帖子`;
    latestPostsContainer.insertBefore(searchResultInfo, latestPostsContainer.firstChild);
}

/**
 * 根据板块ID获取板块名称
 * @param {string} sectionId 板块ID
 * @returns {string} 板块名称
 */
function getSectionName(sectionId) {
    const sectionMap = {
        'freshwater': '淡水钓鱼',
        'sea': '海钓',
        'equipment': '装备讨论',
        'technique': '钓技研究'
    };
    
    return sectionMap[sectionId] || sectionId;
}

/**
 * 创建默认帖子数据
 */
function createDefaultPosts() {
    const defaultPosts = [
        {
            id: "1",
            title: "分享：昨天在太湖钓获的大鲫鱼",
            content: `<p>大家好，昨天我去太湖边钓鱼，收获颇丰！其中最大的一条鲫鱼有近2斤重，真是太兴奋了！</p>
                      <p>在此分享一下我的钓鱼技巧：</p>
                      <ul class="list-disc pl-5 my-3">
                          <li>选择了一个背风的位置，水深约2-3米</li>
                          <li>使用的是自制酒米饵料，加了一点蜂蜜</li>
                          <li>鱼竿是碳素5.4米，搭配3号主线和1.5号子线</li>
                          <li>钓点有少量水草，使用了提线钓法</li>
                      </ul>
                      <p>分享几张照片：</p>
                      <div class="grid grid-cols-2 gap-2 my-3">
                          <img src="https://picsum.photos/600/400?fishing1" alt="钓鱼照片" class="rounded-lg">
                          <img src="https://picsum.photos/600/400?fishing2" alt="钓鱼照片" class="rounded-lg">
                      </div>
                      <p>大家有什么好的建议或者想法，欢迎在评论区交流！</p>`,
            author: "水中游龙",
            authorAvatar: "https://picsum.photos/id/22/200/200",
            date: "2025-05-01",
            section: "淡水钓鱼",
            sectionId: "freshwater",
            likes: 24,
            comments: [
                {
                    id: "c1",
                    author: "钓鱼老手",
                    authorAvatar: "https://picsum.photos/id/33/200/200",
                    content: "不错的收获！我也经常去太湖钓鱼，建议可以尝试用蚯蚓做饵，效果也很好。",
                    date: "2025-05-01",
                    likes: 5
                },
                {
                    id: "c2",
                    author: "鲫鱼达人",
                    authorAvatar: "https://picsum.photos/id/44/200/200",
                    content: "请问具体是在太湖哪个位置啊？最近我也想去试试。",
                    date: "2025-05-02",
                    likes: 2
                }
            ],
            views: 156
        },
        {
            id: "2",
            title: "求推荐：适合初学者的海钓装备",
            content: `<p>各位钓友好，我是海钓新手，最近想入手一套适合海钓的装备，但对海钓知识了解不多，希望各位能给点建议。</p>
                      <p>我主要有以下几个问题：</p>
                      <ol class="list-decimal pl-5 my-3">
                          <li>初学者预算2000左右，可以买到什么档次的海竿和轮？</li>
                          <li>海钓主要钓什么类型的鱼？需要准备哪些饵料？</li>
                          <li>有什么注意事项是新手容易忽略的？</li>
                      </ol>
                      <p>感谢各位钓友的建议！</p>`,
            author: "新手钓手",
            authorAvatar: "https://picsum.photos/id/55/200/200",
            date: "2025-05-02",
            section: "海钓",
            sectionId: "sea",
            likes: 15,
            comments: [
                {
                    id: "c3",
                    author: "海钓老炮",
                    authorAvatar: "https://picsum.photos/id/66/200/200",
                    content: "建议买一根2.7米左右的海竿，搭配一个5000型号的纺车轮。初学者可以先从矶钓开始，比较安全也容易上手。",
                    date: "2025-05-02",
                    likes: 8
                }
            ],
            views: 98
        },
        {
            id: "3",
            title: "技巧分享：如何钓好白条",
            content: `<p>白条鱼是淡水中较为常见的小型鱼类，虽然体型小，但钓起来很有乐趣，尤其适合新手练习。今天给大家分享一下我钓白条的一些心得。</p>
                      <h3 class="text-lg font-bold my-2">饵料选择</h3>
                      <p>白条对饵料不是很挑剔，一般的商品饵都可以，但我个人更喜欢用以下配方：</p>
                      <ul class="list-disc pl-5 my-2">
                          <li>颗粒饲料（小颗粒）：40%</li>
                          <li>面粉：30%</li>
                          <li>麝香米：20%</li>
                          <li>红虫粉：10%</li>
                      </ul>
                      <p>混合后加水调制成稍软的状态，这样挂钩时容易散开，吸引鱼群。</p>
                      <h3 class="text-lg font-bold my-2">钓法技巧</h3>
                      <p>白条多在水层中上层活动，所以我通常采用浮漂稍微调高一点的方式，让饵料悬浮在合适的水层。钓白条最重要的是找到鱼窝，一旦找到，往往可以连竿。</p>
                      <p>希望这些技巧对大家有所帮助！</p>`,
            author: "钓鱼老教授",
            authorAvatar: "https://picsum.photos/id/62/200/200",
            date: "2025-05-03",
            section: "钓技研究",
            sectionId: "technique",
            likes: 36,
            comments: [
                {
                    id: "c4",
                    author: "学钓者",
                    authorAvatar: "https://picsum.photos/id/68/200/200",
                    content: "感谢分享！请问这套饵料在什么季节效果最好？",
                    date: "2025-05-03",
                    likes: 2
                },
                {
                    id: "c5",
                    author: "小鱼爱好者",
                    authorAvatar: "https://picsum.photos/id/91/200/200",
                    content: "试过了，效果很好！一个小时钓了二三十尾。",
                    date: "2025-05-04",
                    likes: 5
                }
            ],
            views: 210
        },
        {
            id: "4",
            title: "活动通知：本周日江边垂钓聚会",
            content: `<p>各位钓友，我们将于本周日（2025年5月10日）在市东郊的青山湖举办一次垂钓聚会活动，欢迎大家参加！</p>
                      <h3 class="text-lg font-bold my-2">活动详情</h3>
                      <p><strong>时间：</strong>5月10日上午8点至下午4点</p>
                      <p><strong>地点：</strong>青山湖东岸（具体位置见下方地图）</p>
                      <p><strong>活动内容：</strong></p>
                      <ul class="list-disc pl-5 my-2">
                          <li>自由垂钓交流</li>
                          <li>钓技分享会（中午12点）</li>
                          <li>简单午餐（提供烧烤设备，食材自带）</li>
                          <li>钓获评比（下午3点）</li>
                      </ul>
                      <p><strong>注意事项：</strong></p>
                      <ul class="list-disc pl-5 my-2">
                          <li>请自带钓具和饵料</li>
                          <li>注意安全，特别是有小孩同行的钓友</li>
                          <li>保持环境整洁，垃圾带走</li>
                      </ul>
                      <p>有意参加的钓友请在评论区回复，方便我们统计人数。期待与大家相聚青山湖畔！</p>`,
            author: "活动组织者",
            authorAvatar: "https://picsum.photos/id/25/200/200",
            date: "2025-05-04",
            section: "社区活动",
            sectionId: "community",
            likes: 29,
            comments: [
                {
                    id: "c6",
                    author: "快乐钓鱼人",
                    authorAvatar: "https://picsum.photos/id/29/200/200",
                    content: "计划参加，携带一位新手朋友，共2人。",
                    date: "2025-05-04",
                    likes: 1
                },
                {
                    id: "c7",
                    author: "老钓手",
                    authorAvatar: "https://picsum.photos/id/42/200/200",
                    content: "我会带上自制饵料来分享，请问有几点停车位？",
                    date: "2025-05-05",
                    likes: 3
                }
            ],
            views: 187
        }
    ];
    
    localStorage.setItem('forumPosts', JSON.stringify(defaultPosts));
}

/**
 * 格式化日期
 * @param {string} dateString ISO格式日期字符串
 * @returns {string} 格式化后的日期字符串
 */
function formatDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    
    // 如果是今天
    if (date.toDateString() === now.toDateString()) {
        return '今天 ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
    }
    
    // 如果是昨天
    const yesterday = new Date();
    yesterday.setDate(now.getDate() - 1);
    if (date.toDateString() === yesterday.toDateString()) {
        return '昨天 ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
    }
    
    // 其他日期
    return date.toLocaleDateString('zh-CN', {year: 'numeric', month: 'long', day: 'numeric'});
}

/**
 * 显示通知
 * @param {string} message 通知消息
 * @param {string} type 通知类型
 */
function showNotification(message, type = 'success') {
    // 创建通知元素，如果不存在
    let notification = document.getElementById('notification');
    
    if (!notification) {
        notification = document.createElement('div');
        notification.id = 'notification';
        notification.className = 'fixed bottom-4 right-4 p-4 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 z-50 hidden';
        document.body.appendChild(notification);
    }
    
    // 设置内容和样式
    notification.textContent = message;
    
    // 根据类型设置背景色
    notification.className = 'fixed bottom-4 right-4 p-4 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 z-50';
    
    if (type === 'error') {
        notification.classList.add('bg-red-500', 'text-white');
    } else if (type === 'warning') {
        notification.classList.add('bg-yellow-500', 'text-white');
    } else {
        notification.classList.add('bg-green-500', 'text-white');
    }
    
    // 显示通知
    notification.classList.remove('hidden', 'translate-y-20', 'opacity-0');
    
    // 3秒后隐藏
    setTimeout(() => {
        notification.classList.add('translate-y-20', 'opacity-0');
        setTimeout(() => {
            notification.classList.add('hidden');
        }, 300);
    }, 3000);
}
